new Vue({
  el: '#app',
  data() {
    return {
      form: {
        Start_Date: '',
        End_Date: '',
        Article_Name: '',
        Row_Status: '',
        Order_Type: "0",
        Enterprise_Info_SerialNumber: $.cookie("enterprise"),
        token: $.cookie("token"),
        Dealer_SerialNumber: '',
        Supplier_SerialNumber: '',
        page: 1,			//页数
        limit: 10,		//每页数据条数
      },
      total: 0,// 总条数
      tableData: [], //表格数据
      MyDate: null,//根据时间筛选
      activeName: ' ',
      menuList: [],//经销商树tree
      loading: false,//懒加载
      supplier: [{ Supplier_SerialNumber: '', Supplier_Name: '全部供应商' }],//供应商订单
      dialogVisible: false,
      pickerOptionsTwo: pickerOptionsTwo,//时间选择器，范围选择
      dialogVisible2: false,//提交订单
      multipleSelection: [],//分配供应商
      form3: {//分配供应商
        Supplier_SerialNumber: '',
        Sales_Order_Detail_SerialNumber: '',
        Store_SerialNumber: '',
        Article_SerialNumber: '',
        Purchase_Unit_Price: '',
        Quantity: '',
        Enterprise_Info_SerialNumber: ''
      },
      sales_order_logistics: [{//物流明细
        disabled1: false,  // 禁用物流公司
        Sales_Order_Logistics_SerialNumber: '', //主键
        Sales_Order_SerialNumber: '',   //销售单号
        LogisticsNumbers: '',  //物流单号
        LogisticsCode: '',  //快递公司
        Quantity: '',   //数量
      }],
      expressCompany: [], // 快递公司
      Quantity: 0,//数量
      checked: false,//
      isdelivery: false,//物流明细
      distributors: [],//经销商
      sales_receipt: {//出库单
        Sales_Receipt_SerialNumber: '',//主键
        Receipt_Date: '',//出库日期
        Receipt_Type: "0",//出货地点
        Receipt_Name: "",
        Store_SerialNumber: "",//仓库编号
        Store_Name: "",
        Enterprise_Info_SerialNumber: "",//企业主键
        Children: {
          sales_receipt_detail: [
            {
              Sales_Receipt_Detail_SerialNumber: "",//主键
              Sales_Receipt_SerialNumber: "",//外键
              Order_Type: "1",//订单类型
              Sales_Order_SerialNumber: "",//销售订单流水号
              Article_SerialNumber: "",//商品流水号
              Article_Name: "",
              Receipt_Quantity: "",//出库数量
              // Amount:"",//商品单价
              Order_Name: "",
              Logistics_Number: "",//物流单号
            }
          ]
        }
      },
      purchase_receipt: {//入库单
        Purchase_Receipt_SerialNumber: "",
        Receipt_Date: "",
        Receipt_Type: 0,
        Store_SerialNumber: "",
        Children: {
          purchase_receipt_detail: [{
            Purchase_Receipt_Detail_SerialNumber: "",
            Purchase_Receipt_SerialNumber: "",
            Purchase_Order_SerialNumber: "",
            Article_SerialNumber: "",//商品建
            Receipt_Quantity: "",//入库数量
            Remain_Quantity: "",//剩余数量
            Out_Total_Quantity: "",//出库数量
            Amount: "",//价格
            Expiration_Date: "",//过期时间
          }]
        }
      },
      delivery: {//手工发货

      },
      Selection:[]//勾选中的
    }
  },
  mounted() {
    this.getData();
    this.loading = true
    this.getList(this.form);
  },
  computed: {
    Row_Name() {
      return function (Refund_Type, Row_Status) {
        try {
          if (Refund_Type == 0 && Row_Status == 1) { return '已付款' }
          else if (Refund_Type == 0 && Row_Status == 0) { return '未付款' }
          else if (Refund_Type == 0 && Row_Status == 4) { return '已退款' }
          else if (Refund_Type == 0 && Row_Status == 6) { return '发货中' }
          else if (Refund_Type == 0 && Row_Status == 7) { return '已送达' }
          else if (Refund_Type == 0 && Row_Status == 9) { return '待发货' }
          else if (Refund_Type == 1) { return '退款审核' }
          else { return '已取消' }
        } catch (error) {
          return ''
        }
      }
    }
  },
  methods: {
    Add(i){//导入销售订单
      sessionStorage.setItem("OrderType",i)
      window.location.href = './Add.html?OrderType='+i
    },
    getData() {//查询数据
      $.ajax({//经销商
        type: 'POST',
        url: `${DomainName}/getSalesOrderTree?token=${$.cookie('token')}`,
        data: {
          Enterprise_Info_SerialNumber: $.cookie('enterprise')
        },
        success: (Result) => {
          console.log(Result);
          this.menuList = Result.Data
        },
        complete: (XMLHttpRequest) => {
          if (XMLHttpRequest.getResponseHeader("REDIRECT") == "REDIRECT") {
            window.parent.document.location.href = absolutepath() + XMLHttpRequest.getResponseHeader("CONTENTPATH");
          }
        },
        dataType: "json"
      });
      $.ajax({//经销商
        type: 'POST',
        url: `${DomainName}/getInquiryAction?token=${$.cookie('token')}`,
        data: {
          Data: 'supplier_info'
        },
        success: (Result) => {
          this.supplier = [...this.supplier, ...Result];
        },
        complete: (XMLHttpRequest) => {
          if (XMLHttpRequest.getResponseHeader("REDIRECT") == "REDIRECT") {
            window.parent.document.location.href = absolutepath() + XMLHttpRequest.getResponseHeader("CONTENTPATH");
          }
        },
        dataType: "json"
      });
      $.ajax({
        type: 'POST',
        url: `${DomainName}/getInquiryAction?token=${$.cookie('token')}`,
        data: {
          Data: 'logistics_company_info',
          isNullEnterprise: true
        },
        success: (data) => {
          this.expressCompany = data
        },
        complete: (XMLHttpRequest) => {
          this.loading = false
          if (XMLHttpRequest.getResponseHeader("REDIRECT") == "REDIRECT") {
            window.parent.document.location.href = absolutepath() + XMLHttpRequest.getResponseHeader("CONTENTPATH");
          }
        },
        dataType: "json"
      });
    },
    getList(data) {//销售订单查询
      $.ajax({
        type: 'POST',
        url: `${DomainName}/getSalesOrderAll1Action?token=${$.cookie('token')}`,
        data,
        success: (Result) => {
          this.tableData = Result.tableData
          this.total = parseInt(Result.limit)
          console.log(Result);
        },
        complete: (XMLHttpRequest) => {
          this.loading = false
          if (XMLHttpRequest.getResponseHeader("REDIRECT") == "REDIRECT") {
            window.parent.document.location.href = absolutepath() + XMLHttpRequest.getResponseHeader("CONTENTPATH");
          }
        },
        dataType: "json"
      });
    },
    handleSelectionChange(val){//勾选订单进行对账
      this.Selection = val
    },
    handleCheckChange() {//获取选中的经销商并查询
      let halfKeys = this.$refs.tree.getHalfCheckedKeys();
      let keys = this.$refs.tree.getCheckedKeys()
      this.throttle(() => {
        let Dealer_SerialNumber = [...keys, ...halfKeys].filter(item => item != "");
        this.form.page = 1;
        if (Dealer_SerialNumber.length > 0) {
          this.form.Dealer_SerialNumber = JSON.stringify(Dealer_SerialNumber)
        } else {
          this.form.Dealer_SerialNumber = '';
        }
        this.loading = true
        this.getList(this.form);
      }, 50)
    },
    handleClick() {//切换导航栏并查询
      this.form.page = 1
      this.form.Row_Status = this.activeName.trim();
      this.loading = true
      this.getList(this.form);
    },
    handleSupplier(e) {//查询供应商
      this.form.page = 1
      this.form.Supplier_SerialNumber = e.name
      this.loading = true
      this.getList(this.form);
    },
    onSerach() {//筛选查询方法
      if (this.MyDate) {
        this.form.Start_Date = this.MyDate[0]
        this.form.End_Date = this.MyDate[1]
      } else {
        this.form.Start_Date = ''
        this.form.End_Date = ''
      }
      console.log(this.MyDate);
      this.form.page = 1
      this.loading = true
      this.getList(this.form)
    },
    handleExpandChange(row, expandedRows) {//展开查询订单明细
      //判断当前表格是否展开
      if (expandedRows.some(item => item.Collection_SerialNumber == row.Collection_SerialNumber)) {
        $.ajax({
          type: 'POST',
          url: `${DomainName}/getSalesOrderDetailID1Action?token=${$.cookie('token')}`,
          data: {
            Start_Date: this.form.Start_Date,
            End_Date: this.form.End_Date,
            Article_Name: this.form.Article_Name,
            Row_Status: this.form.Row_Status,
            Enterprise_Info_SerialNumber: this.form.Enterprise_Info_SerialNumber,
            Collection_SerialNumber: row.Sales_Order_SerialNumber,
            Dealer_SerialNumber: this.form.Dealer_SerialNumber
          },
          success: (Result) => {
            row.Children.sales_order_detail = Result.Data
            console.log(row.Children.sales_order_detail);
          },
          complete: (XMLHttpRequest) => {
            this.loading = false
            if (XMLHttpRequest.getResponseHeader("REDIRECT") == "REDIRECT") {
              window.parent.document.location.href = absolutepath() + XMLHttpRequest.getResponseHeader("CONTENTPATH");
            }
          },
          dataType: "json"
        });
      }
    },
    throttle(callback, delay = 50) {//节流阀
      let oTimeout = null;
      if (!this.changeWait) {
        this.changeWait = true;
        oTimeout = setTimeout(() => {
          callback();
          this.changeWait = false;
        }, delay);
      } else {
        clearTimeout(oTimeout);
      }
    },
    ribao() {
      let _this = this
      $.ajax({
        type: 'GET',
        url: DomainName + '/WeChatDailyReport',
        success: function (res) {
          _this.$message({
            type: 'success',
            message: '发放成功！'
          });
        },
        complete: function (XMLHttpRequest) {
          this_.loading = false
          if (XMLHttpRequest.getResponseHeader("REDIRECT") == "REDIRECT") {
            window.parent.document.location.href = absolutepath() + XMLHttpRequest.getResponseHeader("CONTENTPATH");
          }
        },
        dataType: "json"
      });
    },
    deleteRow(index, rows) {
      console.log(index, 'aaaaa', rows);
      rows.splice(index, 1);
    },
    MaintenanceArticle(row){//
      this.Maintenance({
        Type:'0',
        Sales_Order_SerialNumber:row.Sales_Order_SerialNumber
      },(res)=>{
        if(res.Status == 'success'){
          this.$message({
            type: 'success',
            message: '维护成功'
          }); 
          this.getList(this.form)
        }else{
          this.$confirm('当前订单商品信息没有维护, 是否前往维护?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            window.location.href = '../../ShopManage/DealerArticleConfig/DealerArticleConfig.html';
          }).catch(() => {
            this.$message({
              type: 'info',
              message: '已取消'
            });          
          });
         
        }
      })
    },
    MaintenancePrice(row){//维护导入订单
      this.Maintenance({
        Type:'1',
        Sales_Order_SerialNumber:row.Sales_Order_SerialNumber
      },(res)=>{
        if(res.Status == 'success'){
          this.$message({
            type: 'success',
            message: '维护成功'
          });  
          this.getList(this.form)
        }else{
          this.$confirm('当前订单商品信息没有批发价格单, 是否前往维护?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            window.location.href = '../../ShopManage/PriceManage/WholesalePrice/WholesalePrice.html';
          }).catch(() => {
            this.$message({
              type: 'info',
              message: '已取消'
            });          
          });
         
        }
      })
    },
    Maintenance(data,callback){
      $.ajax({
        type: 'POST',
        url: DomainName + "/MaintenanceSalesOrder?token=" + $.cookie('token'),
        data,
        success: function (res) {
          callback(res)
        },
        complete: function (XMLHttpRequest) {
          if (XMLHttpRequest.getResponseHeader("REDIRECT") == "REDIRECT") {
            window.parent.document.location.href = absolutepath() + XMLHttpRequest.getResponseHeader("CONTENTPATH");
          }
        },
        dataType: "json"
      });
    },
    Reconciliation(){//对账
      if (this.Selection.length>0) {
        if(!checkPropertiesEquality(this.Selection,'Store_SerialNumber')){
          this.$message({
            type: 'error',
            message: '已选中的订单不是同一个销售点'
          }); 
          return;
        }
        this.$confirm('是否将勾选的订单进行对账?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.loading = true;
          $.ajax({
            type: 'POST',
            url: DomainName + '/SalesReconciliation?token=' + $.cookie('token'),
            data: {
              Data:JSON.stringify(this.Selection.filter(item=>item.Store_SerialNumber.charAt(0)!='E'))
            },
            success: (res)=> {
              if (res.Status == 'success') {
                this.$message({
                  type: 'success',
                  message: '成功'
                }); 
                this.getList(this.form)
              }else{
                this.$message({
                  type: 'warning',
                  message: res.Cause
                }); 
                this.getList(this.form)
              }
            },
            complete: (XMLHttpRequest)=> {
              if (XMLHttpRequest.getResponseHeader("REDIRECT") == "REDIRECT") {
                window.parent.document.location.href = absolutepath() + XMLHttpRequest.getResponseHeader("CONTENTPATH");
              }
            },
            dataType: "json"
          });
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消'
          });          
        });
      }else{
        this.$message({
          type: 'error',
          message: '请先选择订单'
        }); 
      }
    },
    changeTime() {
      console.log(this.Start_Date, this.End_Date)
    },
    handleChildren(row) {//供应商销售订单展开明细
      let this_ = this
      $.ajax({
        type: 'POST',
        url: DomainName + '/getPurchaseOrderPaystagesAction?token=' + $.cookie('token'),
        data: {
          Purchase_Order_SerialNumber: row.Purchase_Order_SerialNumber
        },
        success: function (res) {
          row.Children.purchase_order_paystages = res.Data
        },
        complete: function (XMLHttpRequest) {
          this_.loading = false
          if (XMLHttpRequest.getResponseHeader("REDIRECT") == "REDIRECT") {
            window.parent.document.location.href = absolutepath() + XMLHttpRequest.getResponseHeader("CONTENTPATH");
          }
        },
        dataType: "json"
      });
    },
    handleFilterSupplier(e, row) {
      row.supplier = this.supplier.filter(item => item.Supplier_SerialNumber == e)[0];
      this.form3.Purchase_Unit_Price = this.supplier.filter(item => item.Supplier_SerialNumber == e)[0].Purchase_Unit_Price
      this.form3.Article_SerialNumber = this.supplier.filter(item => item.Supplier_SerialNumber == e)[0].Article_SerialNumber
      this.form3.Article_Specifications_SerialNumber = this.supplier.filter(item => item.Supplier_SerialNumber == e)[0].Article_Specifications_SerialNumber
      this.form3.Unit_Price = this.supplier.filter(item => item.Supplier_SerialNumber == e)[0].Unit_Price
    },
    addContract() {
      console.log("跳转")
    },
    handleSizeChange(val) {
      this.form.page = 1;
      this.form.limit = val;
      this.getList(this.form)
    },
    handleCurrentChange(val) {
      this.form.page = val;
      this.getList(this.form)
    },
    subFile() {
      console.log($.cookie("token"))
      let _this = this
      var file = document.getElementById('inputfile').files[0]; // 获取选择的文件
      if (!file) return;
      var reader = new FileReader();
      reader.readAsBinaryString(file);
      reader.onload = function (e) {
        var data = e.target.result;
        var wb = XLSX.read(data, {
          type: 'binary' //以二进制的方式读取
        });
        var sheet0 = wb.Sheets[wb.SheetNames[0]];//sheet0代表excel表格中的第一页
        var str = XLSX.utils.sheet_to_json(sheet0);//利用接口实现转换。
        str.forEach(item => {
          let obj = _this.isArticle(item['规格编码']);
          let Dealer = _this.isDealer(item['经销商'])
          let Abnormal = [obj.abnormal, Dealer.abnormal]
          _this.form2.push({
            Dealer_Order_SerialNumber: item['订单号'],
            Sales_Contacts: item['收货人'],
            Sales_Phone: item['手机号码'],
            Sales_Address: item['收货地址'].replaceAll(' ', '/'),
            Specifications_Name: Object.keys(obj.article).length != 0 ? obj.article.Article_Name : '异常数据(' + item['商品规格名称'] + ')',
            Gfbm: Object.keys(obj.article).length != 0 ? obj.article.Dealer_Article_SerialNumber : '异常数据(' + item['规格编码'] + ')',
            Quantity: item['发货数量'],
            Sales_Message: item['用户备注'],
            Amount: Object.keys(obj.article).length != 0 ? obj.article.Dealer_Amount * item['发货数量'] : '',
            Sales_Amount: Object.keys(obj.article).length != 0 ? obj.article.Dealer_Amount * item['发货数量'] : '',
            Collection_Amount: '0',
            Dealer_SerialNumber: Dealer.Dealer_SerialNumber,
            Dealer_Name: item['经销商'],
            Article_Name: Object.keys(obj.article).length != 0 ? obj.article.Article_Name : '异常数据(' + item['商品名称'] + ')',
            Article_SerialNumber: Object.keys(obj.article).length != 0 ? obj.article.Article_SerialNumber : '',
            Article_Specifications_SerialNumber: Object.keys(obj.article).length != 0 ? obj.article.Article_Specifications_SerialNumber : '',
            Sales_Unit_Price: Object.keys(obj.article).length != 0 ? obj.article.Dealer_Amount : '',
            Abnormal: !Abnormal.some(item => item == false),
          })
        })
      }
      console.log(_this.form2);
    },
    isArticle(str) {
      if (this.article.some(item => item.Dealer_Article_SerialNumber == str)) {
        return { article: this.article.filter(item => item.Dealer_Article_SerialNumber == str)[0], abnormal: true }
      } else {
        return { article: {}, abnormal: false }
      }
    },
    isDealer(str) {
      if (this.dealer.some(item => item.Dealer_Name == str)) {
        return { Dealer_SerialNumber: this.dealer.filter(item => item.Dealer_Name == str)[0].Dealer_SerialNumber, abnormal: true }
      } else {
        return { Dealer_SerialNumber: '异常数据(' + str + ')', abnormal: false }
      }
    },//订单导入
    tableCellStyle({ row, column, rowIndex, columnIndex }) {
      if (!row.Abnormal) return { backgroundColor: '#E6A23C' }
    },
    //退货入库
    ReturnWarehousing(Order_SerialNumber, Type) {
      let _this = this;
      $.ajax({
        type: 'POST',
        data: {
          Order_SerialNumber,
          Type,
        },
        url: DomainName + '/setDeliveryOrderEditType?token=' + $.cookie("token"),
        success: function (res) {
          if (res.Status == 'success') {
            _this.$message({
              type: 'success',
              message: "提交成功"
            });
            _this.getList(_this.form);
          }
        },
        complete: function (XMLHttpRequest) {
          _this.loading = false
          if (XMLHttpRequest.getResponseHeader("REDIRECT") == "REDIRECT") {
            window.parent.document.location.href = absolutepath() + XMLHttpRequest.getResponseHeader("CONTENTPATH");
          }
        },
        dataType: "json"
      });
    },
    // 已发货
    onShipped(row) {
      this.delivery = row
      this.isdelivery = true
    },
    handleManual(row) {//手工发货
      this.$prompt('请输入物流编号', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
      }).then(({ value }) => {
        this.setPurchaseOrderEditType({
          Purchase_Order_Detail_SerialNumber:row.Purchase_Order_Detail_SerialNumber,
          Enterprise_Info_SerialNumber:$.cookie('enterprise'),
          Type:'4',
          Logistics:JSON.stringify({
            Logistics_Date:getYMDHMSDate(),
            Logistics_Number:value
          })
        },(data)=>{
          if(data.Status == 'success'){
            this.$message({
              type: 'success',
              message: '发货成功'
            });
            this.getList(this.form)
          }
        })
      }).catch(() => {
        this.$message({
          type: 'danger',
          message: '取消发货'
        });
      });
    },
    setPurchaseOrderEditType(data,callback) {//修改采购订单
      $.ajax({
        type: 'POST',
        data,
        url: DomainName + '/setPurchaseOrderEditType?token='+$.cookie('token'),
        success: function (data) {
          callback(data)
        },
        complete: function (XMLHttpRequest) {
          if (XMLHttpRequest.getResponseHeader("REDIRECT") == "REDIRECT") {
            window.parent.document.location.href = absolutepath() + XMLHttpRequest.getResponseHeader("CONTENTPATH");
          }
        },
        dataType: "json"
      });
    },
    addOddNumbers() {
      var Num = 0
      this.sales_order_logistics.forEach(item => {
        item.Sales_Order_SerialNumber = this.delivery.Sales_Order_Detail_SerialNumber
        Num = Num + Number(item.Quantity)
      })
      console.log(Num);
      console.log(this.sales_order_logistics);
      if (Num != this.delivery.Quantity) {
        this.$message({
          type: 'error',
          message: '输入的数据有误'
        });
      } else {
        this.loading = true;
        this.setSalesOrderEditType({
          Sales_Order_Detail_SerialNumber: this.delivery.Sales_Order_Detail_SerialNumber,
          Type: '6',
          Logistics: JSON.stringify(this.sales_order_logistics)
        }, () => {
          this.isdelivery = false
          this.$message({
            type: 'success',
            message: '发货成功'
          })
          this.getList(this.form)
        })
      }
    },
    // 清空物流信息
    qing_sales_order_logistics() {
      this.sales_order_logistics = [{     //采购价格单
        Sales_Order_Logistics_SerialNumber: '', //主键
        Sales_Order_SerialNumber: '',   //销售价格单号
        LogisticsNumbers: '',  //快递公司
        LogisticsCode: '',  //物流单号
        Quantity: '',   //数量
      }]
      this.checked = false
    },
    // 已送达
    delivered(row) {
      let _this = this;
      if (row.Row_Status == '6') {
        this.$confirm('更改订单状态为\'已送达\', 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
          center: true
        }).then(() => {
          _this.setSalesOrderEditType({
            Sales_Order_Detail_SerialNumber: row.Sales_Order_Detail_SerialNumber,
            Type: '7'
          }, (data) => {
            if (data.Status === 'success') {
              _this.$message({
                type: 'success',
                message: '提交成功',
              });
              _this.getList(_this.form)
            } else {
              _this.$message({
                type: 'error',
                message: '提交失败',
              });
            }
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消！'
          });
        });
      }
    },
    // 是否自提
    SelfPickup() {
      this.sales_order_logistics.forEach(item => {
        if (this.checked) {
          item.disabled1 = true
          item.LogisticsCode = ''
          item.LogisticsNumbers = '自提'
        } else {
          item.disabled1 = false
          item.LogisticsNumbers = ''
        }
      })
    },
    // 新增物流信息
    add_sales_order_logistics() {
      if (this.Quantity == this.sales_order_logistics.length) {
        this.$message({
          message: `总数为${this.Quantity},不可以在新增了`,
          type: 'warning'
        })
        return
      }
      this.sales_order_logistics.push({     //采购价格单
        Sales_Order_Logistics_SerialNumber: '', //主键
        Sales_Order_SerialNumber: '',   //销售价格单号
        LogisticsNumbers: '',  //快递公司
        LogisticsCode: '',  //物流单号
        Quantity: '',   //数量
        checked: false
      })
    },
    remove_sales_order_logistics() {
      if (this.sales_order_logistics.length > 1) {
        this.sales_order_logistics.pop()
      } else {
        this.$message({
          message: '不能在删除了',
          type: 'warning'
        })
      }
    },
    //分配供应商信息
    DistributionSupplier(row) {
      //分配供应商
      if (row.Sign == "无货货主") {
        if (row.Row_Status == '1'&& row.Store_SerialNumber.charAt(0)=='E' || row.Row_Status == '9'&& row.Store_SerialNumber.charAt(0)=='E'||row.Row_Status == '0'&& row.Store_SerialNumber.charAt(0)!='E') {
          if (row.Article_SerialNumber.split('-')[2] != $.cookie('enterprise')) {
            return this.$message.error("该商品供应商是外企业，不可更改")
          } else {
            this.PurchaseSupplier(row, (data) => {
              if (data.length == 1) {
                //自动更新状态
                this.setSalesOrderEditType({
                  Sales_Order_Detail_SerialNumber: row.Sales_Order_Detail_SerialNumber,
                  Suppliers: JSON.stringify(data[0]),
                  Type: '9'
                }, (data) => {
                  if (data.Status == 'success') {
                    this.$message({
                      message: '分配成功',
                      type: 'success'
                    })
                    this.getList(this.form)
                  }
                });
              } else if (data.length == 0) {//提示暂无可分配供应商
                this.$message({
                  message: '当前商品暂无供应商，请添加采购价格单',
                  type: 'error'
                })
              } else {//手动分配
                this.dialogVisible2 = true
              }
            })
            // this.multipleSelection = []
            // this.supplier = []
            // this.form3 = {}
          }
        } else {
          this.$message.error("该订单状态不满足分配供应商条件")
        }
      } else if (row.Sign == '有货货主') {
        this.setSalesOrderEditType({
          Sales_Order_Detail_SerialNumber: row.Sales_Order_Detail_SerialNumber,
          Type: '9'
        }, (data) => {
          if (data.Status == 'success') {
            this.$message({
              message: '已通知发货',
              type: 'success'
            })
            this.getList(this.form)
          }
        })
      }
    },
    //选择供应商后提交信息
    submitForm() {
      let _this = this
      if (!_this.form3.Supplier_SerialNumber) return _this.$message('请选择供应商');
      // 更改状态
      if (this.form.Order_Type == '0') {
        let row = this.multipleSelection[0]
        let obj = row.supplier;
        this.setSalesOrderEditType({
          Sales_Order_Detail_SerialNumber: row.Sales_Order_Detail_SerialNumber,
          Suppliers: JSON.stringify(obj),
          Type: '9'
        }, (data) => {
          if (data.Status == 'success') {
            this.getList(_this.form);
          }
        });
      } else {
        let row = this.multipleSelection[0]
        let obj = row.supplier;
        this.setPurchaseOrderAction(row, obj);
      }
    },
    setSalesOrderEditType(data, callback) {//修改销售订单状态
      let _this = this;
      _this.loading = true
      $.ajax({
        type: 'POST',
        data,
        url: DomainName + '/setSalesOrderEditType?token=' + $.cookie('token'),
        success: function (data) {
          callback(data)
        },
        complete: function (XMLHttpRequest) {
          if (XMLHttpRequest.getResponseHeader("REDIRECT") == "REDIRECT") {
            window.parent.document.location.href = absolutepath() + XMLHttpRequest.getResponseHeader("CONTENTPATH");
          }
        },
        dataType: "json"
      });
    },
    PurchaseSupplier(row, callback) {
      let _this = this
      if (row.Row_Status == '1'&& row.Store_SerialNumber.charAt(0)=='E'||row.Row_Status == '0'&& row.Store_SerialNumber.charAt(0)!='E') {
        //初始化
        this.multipleSelection = []
        this.supplier = []
        // 获取卖此商品供应商
        $.ajax({
          type: 'POST',
          data: {
            Article_SerialNumber: row.Article_SerialNumber,
            Enterprise_Info_SerialNumber: this.form.Order_Type == "0" ? row.Enterprise_Info_SerialNumber : row.Settled_Enterprise_Info_SerialNumber
          },
          url: DomainName + '/getSupplierArticleAction?token=' + $.cookie("token"),
          success: function (data) {
            _this.supplier = data
            callback(data)
          },
          complete: function (XMLHttpRequest) {
            if (XMLHttpRequest.getResponseHeader("REDIRECT") == "REDIRECT") {
              window.parent.document.location.href = absolutepath() + XMLHttpRequest.getResponseHeader("CONTENTPATH");
            }
          },
          dataType: "json"
        });
        //获取数据
        this.multipleSelection.push(row)
      } else {
        this.$message.error("该订单状态不满足分配供应商条件")
      }
    },
    refund(Sales_Order_SerialNumber) {
      let _this = this
      this.$confirm('提交退款申请, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        center: true
      }).then(() => {
        $.ajax({
          type: 'POST',
          data: {
            Sales_Order_SerialNumber: Sales_Order_SerialNumber,
            token: $.cookie("token")
          },
          url: DomainName + '/getChatRefundNativeAction',
          success: function (data) {
            if (data.Status === 'success') {
              _this.$message({
                type: 'success',
                message: '提交成功'
              });
              _this.getList(_this.form)
            } else {
              _this.$message({
                type: 'info',
                message: '提交失败'
              });
            }
          },
          complete: function (XMLHttpRequest) {
            _this.loading = false
            if (XMLHttpRequest.getResponseHeader("REDIRECT") == "REDIRECT") {
              window.parent.document.location.href = absolutepath() + XMLHttpRequest.getResponseHeader("CONTENTPATH");
            }
          },
          dataType: "json"
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消提交退款申请！'
        });
      });
    },
    showMember(Sales_Order_SerialNumber) {
      sessionStorage.setItem("Sales_Order_SerialNumber", Sales_Order_SerialNumber)
      window.location.href = './show.html?Sales_Order_SerialNumber=' + Sales_Order_SerialNumber
    },
    validate(arr) {
      if (arr[0] == undefined || arr[1] == undefined) {
        this.$message.error('请选择开始时间和结束时间')
        return false
      } else if (arr[0] != undefined && arr[1] != undefined) {
        return true
      }
    },
    // 时间筛选
    onDetails() {
      if (this.validate(this.time)) {
        sessionStorage.setItem("start-date", this.time[0])
        sessionStorage.setItem("end-date", this.time[1])
        // window.location.href = '../xiaoshouDetails/Details.html'
      }
    },
    beforeRemove(file, fileList) {
      this.fileList.pop()
      this.form2 = []
    },
    onExcel() {
      /* generate workbook object from table */
      //  .table要导出的是哪一个表格
      var wb = XLSX.utils.table_to_book(document.querySelector("#out-table"));
      /* get binary string as output */
      var wbout = XLSX.write(wb, {
        bookType: "xlsx",
        bookSST: true,
        type: "array"
      });
      try {
        //  name+'.xlsx'表示导出的excel表格名字
        saveAs(
          new Blob([wbout], {
            type: "application/octet-stream"
          }),
          "销售订单" + ".xlsx"
        );
      } catch (e) {
        if (typeof console !== "undefined") console.log(e, wbout);
      }
      return wbout;
    },
    uploadDetails(file) {
      this.fileList.push({
        name: file.name,
        url: file.type
      })
      let _this = this
      var reader = new FileReader();
      reader.readAsBinaryString(file);
      reader.onload = function (e) {
        var data = e.target.result;
        var wb = XLSX.read(data, {
          type: 'binary' //以二进制的方式读取
        });
        var sheet0 = wb.Sheets[wb.SheetNames[0]];//sheet0代表excel表格中的第一页
        var str = XLSX.utils.sheet_to_json(sheet0);//利用接口实现转换。
        console.log(str);
        //将整体数据分解成每一条，一条上传一次

        //1.将接受到数组便利
        str.forEach(item => {
          _this.form2.push({
            Sales_Order_SerialNumber: item['订单号'],
            Sales_Contacts: item['收货人'],
            Sales_Phone: item['手机号码'],
            Sales_Address: item['收货地址'],
            Wliugs: item['物流公司'],
            Sqname: item['商品名称'],
            Specifications_Name: item['商品规格名称'],
            Gfbm: item['规格编码'],
            Quantity: item['发货数量'],
            Sales_Message: item['用户备注'],
            Amount: '',
            Sales_Date: '',
            Sales_Amount: '',
            Collection_Amount: '',
            Dealer_Name: '',
            Dealer_SerialNumber: '',
            App_ID: '',
            Article_Name: '',
            Article_SerialNumber: '',
            Article_Specifications_SerialNumber: '',
            Quantity: '',
            Sales_Unit_Price: ''
          })
        })
      }
    },
    handleConfirm(row, Trading_Detail_SerialNumber) {//确认收款信息
      let this_ = this;
      $.ajax({
        url: DomainName + '/getSubtableInquiryOriginal?token=' + $.cookie("token"),
        type: 'POST',
        data: {
          Primary_Key: row.Purchase_Order_SerialNumber,
          JSONObject: JSON.stringify({ purchase_order: { purchase_order_paystages: {} } }),
        },
        success: function (res) {
          if (res.purchase_order.length == 1) {
            let purchase_order = res.purchase_order;
            purchase_order[0].Confirm_Amount = purchase_order[0].Paid_Amount
            purchase_order[0].Children.purchase_order_paystages.forEach(item => {
            if (item.Trading_Detail_SerialNumber == Trading_Detail_SerialNumber && item.Confirm == '0') {
              item.Confirm = '1'
            }
            })
            this_.EditInquiry({ Data: JSON.stringify({ Modify: { purchase_order } }) }, () => {
              this_.getList(this_.form)
              this_.loading = false
              this_.$message({
                message: '成功',
                type: 'success'
              })
            })
          }
        },
        complete: function (XMLHttpRequest) {
          if (XMLHttpRequest.getResponseHeader("REDIRECT") == "REDIRECT") {
            window.parent.document.location.href = absolutepath() + XMLHttpRequest.getResponseHeader("CONTENTPATH");
          }
        },
      })
    },
    handleDelivery(row) {//发货
      //是，直接生成发货订单
      let _this = this;
      if (row.Independence == '0') {
        $.ajax({
          type: 'POST',
          data: {
            Unit_Price_SerialNumber: row.Unit_Price_SerialNumber,
            Purchase_Order_SerialNumber: row.Purchase_Order_SerialNumber,
            Quantity: row.Quantity,
            Packing: row.Packing,
            Independence: row.Independence,
            Article_SerialNumber: row.Article_SerialNumber,
            Collection_Date: row.Collection_Date,
            Enterprise_Info_SerialNumber: $.cookie("enterprise")
          },
          url: DomainName + '/getDeliveryOrderAction?token=' + $.cookie('token'),
          success: function (data) {
            if (data.Status === 'success') {
              _this.getList(_this.form)
            }
          },
          complete: function (XMLHttpRequest) {
            if (XMLHttpRequest.getResponseHeader("REDIRECT") == "REDIRECT") {
              window.parent.document.location.href = absolutepath() + XMLHttpRequest.getResponseHeader("CONTENTPATH");
            }
          },
          dataType: "json"
        });
      } else {//
        //1.获取这个商品供应商
        //判断是否选品池shangp 
        if (row.Article_SerialNumber.split('-')[2] == $.cookie('enterprise')) {
          //是否只有一个供应商
          this.PurchaseSupplier(row, (data) => {
            //是自动分配订单 并复写采购订单
            if (data.length == 1) {
              let obj = data[0]
              this.setPurchaseOrderAction(row, obj);
            } else if (data.length == 0) {//提示暂无可分配供应商
              this.$message({
                message: '当前商品暂无供应商，请添加采购价格单',
                type: 'error'
              })
            } else {//手动分配
              //打开弹窗
              this.dialogVisible2 = true
            }
          })
        } else {//否 自动分配订单 并更新状态
          // this.setPurchaseOrderAction(row, obj);
        }
      }
    },
    //生成采购订单并复写订单状态
    setPurchaseOrderAction(row, obj) {//生成采购订单
      let _this = this;
      this.setPurchaseOrder({
        Data: JSON.stringify({
          purchase_order: [{
            Purchase_Order_SerialNumber: '',
            Supplier_SerialNumber: obj.Supplier_SerialNumber,
            Purchase_Date: getYMDHMSDate(),
            Purchase_Type: '1',
            Purchase_Amount: accMul(row.Quantity, obj.Purchase_Unit_Price),
            Paid_Amount: 0,
            Return_Amount: 0,
            Apply_Amount: 0,
            Confirm_Amount: 0,
            Enterprise_Info_SerialNumber: $.cookie("enterprise"),
            Row_Status: 0,
            Children: {
              purchase_order_detail: [{       //采购订单明细
                Purchase_Order_Detail_SerialNumber: "",
                Purchase_Order_SerialNumber: '',
                Unit_Price_SerialNumber: row.Purchase_Unit_Price_Detail_SerialNumber,//价格单主键
                Brand_SerialNumber: '',
                Article_SerialNumber: obj.Article_SerialNumber,//商品主键
                Article_Specifications_SerialNumber: obj.Article_Specifications_SerialNumber,//规格主键
                Article_UnitPrice: obj.Unit_Price,
                Purchase_UnitPrice: obj.Purchase_Unit_Price,
                Quantity: row.Quantity,
                Store_SerialNumber: "",
                Depot_Type: 2,
                Receipt_Quantity: 0,
                Not_Receipt_Quantity: 0,
                Shippment_Quantity: 0,
                Inventory_Quantity: 0,
                Amount: accMul(row.Quantity, obj.Purchase_Unit_Price),
                Child_Purchase_Order_SerialNumber: row.Purchase_Order_Detail_SerialNumber
              }],
              purchase_order_paystages: [{
                Purchase_Order_Paystages_SerialNumber: '',
                Purchase_Order_SerialNumber: '',
                Trading_Explain: '全款',
                Trading_Detail_SerialNumber: 'T01000000000001',
                Trading_Percentage: '100',
                Trading_Days: '0',
                Purchase_Amount: accMul(row.Quantity, obj.Purchase_Unit_Price),
                Paid_Amount: '0',
                Collection_Date: '',
                Confirm: '0',
              }]
            }
          }]
        })
      }, () => {//1单制
        $.ajax({
          url: DomainName + '/TableIDEdit?token=' + $.cookie("token"),
          type: 'POST',
          data: {
            TableName: 'purchase_order',
            Primary_Key: JSON.stringify({ Purchase_Order_SerialNumber: row.Purchase_Order_SerialNumber }),
            Modify: JSON.stringify({ Row_Status: 3 })
          },
          success: function (res) {
            if (res.Status === 'success') {
              _this.getList(_this.form)
              _this.$message({
                message: '分配成功',
                type: 'success'
              })
            }
          },
          complete: function (XMLHttpRequest) {
            if (XMLHttpRequest.getResponseHeader("REDIRECT") == "REDIRECT") {
              window.parent.document.location.href = absolutepath() + XMLHttpRequest.getResponseHeader("CONTENTPATH");
            }
          },
          dataType: "json"
        });
      })
    },
    setPurchaseOrder(data, callback) {//通用添加
      $.ajax({
        url: DomainName + '/setPurchaseOrderAction?token=' + $.cookie("token"),
        type: 'POST',
        data,
        success: function (res) {
          if (res.Status == 'success') {
            callback()
          }
        },
        dataType: "json"
      });
    },
    EditInquiry(data, callback) {//通用修改
      $.ajax({
        url: DomainName + '/getEditAction?token=' + $.cookie("token"),
        type: 'POST',
        data,
        success: function (res) {
          callback()
        },
        complete: function (XMLHttpRequest) {
          if (XMLHttpRequest.getResponseHeader("REDIRECT") == "REDIRECT") {
            window.parent.document.location.href = absolutepath() + XMLHttpRequest.getResponseHeader("CONTENTPATH");
          }
        },
        dataType: "json"
      });
    },
    RadioChange(e) {//切换用户or经销商
      console.log(e)
      this.tableData = []
      this.form.page = 1
      this.getList(this.form)
      if (e == '1') {
        this.Getdistributors()
      }
    },
    Pricethousands(num) {//转千分位
      return thousands(num)
    },
    SelectDistributors() {
      this.form.page = 1
      this.getList(this.form)
    },
    handlePurchase(row, rowfu) {//经销商明细退款
      // if(row.Row_Status == '1'){
      let this_ = this
      this_.loading = true
      $.ajax({
        url: DomainName + '/getPurchaseWeChatRefundAction?token=' + $.cookie("token"),
        type: 'POST',
        data: {
          Purchase_Order_Paystages_SerialNumber: row.Purchase_Order_Paystages_SerialNumber,
        },
        success: function (res) {
          if (res.Status == 'success') {
            this_.handleChildren(rowfu)
            this_.$message({
              message: '申请成功',
              type: 'success'
            })
          }
        },
        complete: function (XMLHttpRequest) {
          if (XMLHttpRequest.getResponseHeader("REDIRECT") == "REDIRECT") {
            window.parent.document.location.href = absolutepath() + XMLHttpRequest.getResponseHeader("CONTENTPATH");
          }
        },
        dataType: "json"
      });
      // }
    },
    Getdistributors() {//获取所有可选择的经销商
      const _this = this
      $.ajax({
        url: DomainName + '/getInquiryAction?token=' + $.cookie("token"),
        type: 'POST',
        data: {
          Data: 'dealer_info',
        },
        success: function (res) {
          console.log(res)
          _this.distributors = res
        },
        dataType: "json"
      });
    },
  },
})